package com.example.dao;
import com.example.bean.LoginLog;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
// import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

// import java.sql.ResultSet;
// import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

//定义一个Repository：Dao注入
@Repository("LoginLogRepositoryImpl")
public class  LoginLogRepositoryImpl implements LoginLogRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //新增用户的登录记录
    @Override
    public void insertLoginLog(String username, Date logindate) {
        String sql = "INSERT INTO user_login_logs (username, login_date) VALUES (?, ?)";
        Object[] params = {username, logindate};
        jdbcTemplate.update(sql, params);
    }


    //根据用户名查找该用户的所有历史登录记录
    @Override
    public List<LoginLog> findLoginLogsByUsername(String username) {
        String sql = "SELECT * FROM user_login_logs WHERE username = ?";
        return jdbcTemplate.query(sql, new Object[]{username}, (rs, rowNum) -> {
            LoginLog loginLog = new LoginLog();
            loginLog.setUsername(rs.getString("username"));
            loginLog.setLoginDate(rs.getDate("login_date"));
            return loginLog;
        });
    }
    public String formatLoginDate(Date loginDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(loginDate);
    }

}